import math

from symbol_table import SymbolTable
from error import Error
from interpreter import Interpreter, Context, Number
from lexer import Lexer
from parser import Parser, ParserResult
from result import *
from function import BuiltInFunction

# 全局作用域
global_symbol_table = SymbolTable()

# 默认变量 null
global_symbol_table.set('null', Number(0))
global_symbol_table.set('True', Number(1))
global_symbol_table.set('False', Number(0))
# 注册内建函数
global_symbol_table.set("PI", Number.PI)
global_symbol_table.set("print", BuiltInFunction.print)
global_symbol_table.set("input", BuiltInFunction.input)
global_symbol_table.set("clear", BuiltInFunction.clear)
global_symbol_table.set("is_number", BuiltInFunction.is_number)
global_symbol_table.set("is_str", BuiltInFunction.is_string)
global_symbol_table.set("is_list", BuiltInFunction.is_list)
global_symbol_table.set("is_func", BuiltInFunction.is_function)
global_symbol_table.set("append", BuiltInFunction.append)
global_symbol_table.set("pop", BuiltInFunction.pop)
global_symbol_table.set("extend", BuiltInFunction.extend)
global_symbol_table.set("len", BuiltInFunction.len)


def run(fn, text):
    lexer = Lexer(fn, text)  # 创建词法分析器
    tokens, error = lexer.make_tokens()  # 获取分割的 token
    # print("词法解析器生成的tokens: ", tokens)
    # 语法解析器解析成 AST 抽象语法树
    parse = Parser(tokens)
    ast: ParserResult = parse.parse()
    # print("语法解析器生成的AST抽象语法树: ", ast.node)
    # return ast.node, ast.error
    # 解释器获取结果
    interpreter = Interpreter()
    context = Context('<program>')
    context.symbol_table = global_symbol_table
    res: RTResult = interpreter.visit(ast.node, context)
    return res.value, res.error
